package main

import (
	"fmt"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"io/ioutil"
	"net/http"
	"node/gin/conf"
	"node/gin/routers"
	"strings"
	"time"
)

func init() {
	//初始化配置
	c := viper.New()
	_ = c.BindEnv("CONFIGPATH")
	c.SetDefault("CONFIGPATH", "./conf/json")
	configPath := c.GetString("CONFIGPATH")
	fmt.Println(configPath)
	files, _ := ioutil.ReadDir(configPath)
	var configs []conf.Load
	for _, f := range files {
		if strings.HasSuffix(f.Name(), ".json") {
			p := f.Name()[:len(f.Name())-5]
			log.Warn("读取到的配置文件：", p)
			c := conf.FileLoad{
				Name: p,
				Path: configPath,
			}
			configs = append(configs, c.Load)
		}
	}
	conf.Setup(configs...)
}

func main() {
	//加载额外功能
	routers.InitClient()
	routers.InitTimeHandler()

	//启动服务器
	router := routers.InitRouter()
	endPoint := fmt.Sprintf(":%d", conf.Config.Server.Port)
	readTimeout := conf.Config.Server.ReadTimeout
	writeTimeout := conf.Config.Server.WriteTimeout
	s := &http.Server{
		Addr:           endPoint,
		Handler:        router,
		ReadTimeout:    readTimeout * time.Second,
		WriteTimeout:   writeTimeout * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	log.Warn("监听http请求中：")
	_ = s.ListenAndServe()
}
